class Solution {
    public int lastStoneWeightII(int[] stones) {
        int n = stones.length;
        int sum = 0;
        for(int i = 0; i < n; i++) sum += stones[i];
        int aim =  sum / 2;
        int[] dp = new int[aim + 1];
        for(int i = 1; i <= n; i++){
            for(int j = aim; j >= stones[i - 1]; j--){
                dp[j] = Math.max(dp[j], dp[j - stones[i - 1]] + stones[i - 1]);
            }
        }
        return sum - 2 * dp[aim];
    }
}